<template>
  <div>
    <FilterTable
      ref="table"
      columnsRef="repairDispatchSkks"
      :columns="columns"
      selectionType="single"
      :onColumnsChange="columns => (this.columns = columns)"
      :onRowSelectChange="arr => (this.rowSelect = arr)"
      :isExportExcel="true"
      :onSyncTableData="maintenanceSyncDataFun"
      :onCalcExportData="exportFun"
      :fetchapi="fetchApi"
      :params="fetchParams"
      :datakey="'rows'"
      exportFileName="配件综合情况查询-维修领料.xlsx"
    >
      <!-- :dataSource="dataSource" -->
      <!-- :isMemoryPagination="true" -->

      <template slot="controls">
        <AjaxButton size="small" type="primary" :disabled="printFlag" icon="el-icon-printer" :click="printHandle">打印</AjaxButton>
      </template>
      <template slot="controls">
        <AjaxButton size="small" type="primary" icon="el-icon-printer" :click="exportHandle">导出</AjaxButton>
      </template>
    </FilterTable>
    <!-- 一般领料一进一出打印 新 hxj 2020/1/10 -->
    <BasePrint ref="print" :data="printList" destroyOnClose template="templateRepairMaterials" />
    <BasePrint ref="printFu" :data="printList" destroyOnClose template="templateRepairMaterialsExit" />
  </div>
</template>
<script>
import { dictionary } from '@/utils/dictMixin';
import dictCode from '@/utils/dictCode';
import { queryPartInOutStockReport, exportPartInOutStockReport } from '@/api/part/report/billSearch';
import { getStroageList } from '@/api/part/partOutbound/partBreak';
import { getModel } from '@/api/customerRepair/customerCare/insuranceDueRemind/index';
import { getWxlxSelect } from '@/api/repair/repairReception/customer';
import { searchRoleByCode, searchRoleByCodes } from '@/api/common/empSelect/index';
import { isAuthorized, arrayObjDeWeight, notifyAction, exportExcelFile } from '@/utils/index';
import { queryPrintDataByRoNoOutStockNo, getExitPart } from '@/api/part/partOutbound/repairMaterials/index.js';
import { sleep } from '@/utils';
import { dealerPrintApi } from '@/api/repair/index.js';
import { getAllUser, queryTex } from '@/api/part/common';
import favorableModelsVue from '../../../../common/auth/oemRoleManage/components/TodoList/favorableModels.vue';

export default {
  mixins: [dictionary],
  props: {
    fetchParamObj: Object,
    type: String,
    userList: Array
  },

  data() {
    return {
      fetchApi: queryPartInOutStockReport,
      columns: this.createdTable(),
      fetchParams: { xhrAbort: true },
      selectColumns: [],
      cunUserList: [],
      printFlag: false, // 打印按钮
      outOrderPrintData: [], // 打印数据
      rowSelect: [], // 行数据
      printParams: {},
      salerData: [],
      dataSource: [],
      printList: {}
    };
  },
  watch: {
    fetchParamObj(fetchParamObj) {
      // console.log(fetchParamObj, 'fetchParamObj----');
      this.initTableData(fetchParamObj);
    }
  },
  mounted() {
    this.getStorage();
    // this.queryModel();
    // this.getWxtypeSelect();
    // this.serviceConsultant();
    this.getEmployee();
    // this.getPrintParams();
  },
  methods: {
    exportFun(row) {
      let arr = row.CHIEF_TECHNICIAN ? row.CHIEF_TECHNICIAN.split(',') : [];
      let nameArr = [];
      arr.map(item2 => {
        nameArr.push(this.salerData[item2]);
      });
      row.TECHNICIAN_NAMES_TRANSED = nameArr.join(',');
    },
    async getPrintParams() {
      let params = { vModule: '90211009', vNormalCode: 'BJCK' };
      const res = await dealerPrintApi(params);
      if ((res.resultCode == 200) & res.data.length) {
        this.printParams = res.data[0];
      }

      console.log('打印的参数', this.printParams);
    },
    //导出
    async exportHandle(){
      let res = await exportPartInOutStockReport(this.fetchParams);
      console.log(res,"导出::");
      try{
        exportExcelFile(res.data,'维修领料')
      }catch(e){
        console.log(e,"错误::");
      }
    },
    // 打印处理
    printHandle() {
      let outStockNo = '';
      let printFlagZheng = true;
      let printFlagFu = true;
      if (!this.rowSelect.length) {
        this.$notify.error({ title: '提示信息', message: '请至少选择一条需要打印的数据！！！' });
        return;
      }
      let roNo = this.rowSelect[0].RO_NO;
      const element = this.rowSelect[0];
      printFlagZheng = printFlagZheng && element.PART_QUANTITY > 0;
      printFlagFu = printFlagFu && element.PART_QUANTITY < 0;
      if (!printFlagZheng && !printFlagFu) {
        this.$notify.error({ title: '提示信息', message: '不可同时选择退料和领料数据' });
        return;
      }
      outStockNo = element.OUT_STOCK_NO;
      if (!outStockNo.length) {
        this.$notify.error({ title: '提示信息', message: '选择的项目中没有发料单号，无法打印！！！' });
        return;
      }
      this.queryPrintDataByRoNoOutStockNo(roNo, outStockNo, printFlagZheng, printFlagFu);
    },
    async queryPrintDataByRoNoOutStockNo(roNo, outStockNo, printFlagZheng, printFlagFu) {
      let res = {};
      if (printFlagZheng) {
        res = await queryPrintDataByRoNoOutStockNo({ roNo, outStockNo });
      }
      if (printFlagFu) {
        res = await getExitPart({ roNo, outStockNo });
      }
      console.log(res.data);
      if (res.resultCode == 200) {
        // 翻译服务顾问和技师
        if (res.data) {
          let serviceAdvisor = this.cunUserList[res.data.SERVICE_ADVISOR];
          let chiefTechnician = this.cunUserList[res.data.CHIEF_TECHNICIAN];
          res.data.SERVICE_ADVISOR = serviceAdvisor ? serviceAdvisor.text : res.data.SERVICE_ADVISOR;
          res.data.CHIEF_TECHNICIAN = chiefTechnician ? chiefTechnician.text : res.data.CHIEF_TECHNICIAN;

          let sender = this.cunUserList[res.data.SENDER];
          let receiver = this.cunUserList[res.data.RECEIVER];
          res.data.SENDER = sender ? sender.text : res.data.SENDER;
          res.data.RECEIVER = receiver ? receiver.text : res.data.RECEIVER;
        }
        // 翻译发料人和领料人
        if (res.data && res.data.items.length) {
          res.data.items.forEach(x => {
            let sender = this.cunUserList[x.SENDER];
            let receiver = this.cunUserList[x.RECEIVER];
            x.SENDER = sender ? sender.text : x.SENDER;
            x.RECEIVER = receiver ? receiver.text : x.RECEIVER;
          });
        }
        this.printList = res.data;
        console.log(this.printList, 'hexj0001');
        if (printFlagZheng) {
          this.$refs.print.EXCUTE_PRINT();
        }
        if (printFlagFu) {
          this.$refs.printFu.EXCUTE_PRINT();
        }
      }
    },
    // 查询打印数据并处理
    async queryPrintDataAndPrint(roNo, outStockNo) {
      let res = await queryPrintDataByRoNoOutStockNo({ roNo, outStockNo });
      if (res.resultCode == 200) {
        // 手动翻译部分数据
        if (res.data.items && res.data.items[0]) {
          res.data.PICK_TYPE_NAME = this.createDictText(res.data.items[0].PICK_TYPE, '8111');
        }
        // 获取库管员
        try {
          let roleParam = { role: dictCode.STORE_KEEPER };
          let storeKeeperData = await searchRoleByCode(roleParam);
          res.data.STORE_KEEPER_NAME = this.userList[res.data.CREATED_BY];
        } catch (err) {
          console.log(err, '获取库管员失败');
        }
        // 翻译人名
        res.data.RECEIVER_NAME = this.userList[res.data.RECEIVER];
        res.data.SENDER_NAME = this.userList[res.data.SENDER];
        this.outOrderPrintData = res.data;
        this.outOrderPrintData.MODEL_NAME = this.selectColumns[0].MODEL_NAME;
        this.$refs.outOrderPrint.EXCUTE_PRINT();
      }
    },
    createdTable() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 70,
          sorter: true,
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '出库单编号',
          dataIndex: 'OUT_STOCK_NO',
          sorter: true,
          filter: true,
          filterType: 'input',
          showOverflowTooltip: true
        },
        // {
        //   title: '原单编号',
        //   dataIndex: 'fake1',
        //   sorter: true,
        //   filter: true,
        //   filterType: 'input',
        //   showOverflowTooltip: true
        // },
        {
          title: '对应单编号',
          dataIndex: 'RO_NO',
          sorter: true,
          filter: true,
          filterType: 'input',
          showOverflowTooltip: true
        },
        // {
        //   title: '出库方式',
        //   dataIndex: 'PICK_TYPE',
        //   render: params => {
        //     return <span>{this.createDictText(params.row.PICK_TYPE, '8111')}</span>;
        //   },
        //   sorter: true,
        //   filter: true,
        //   filterType: 'checkbox',
        //   filterItems: this.createDictList('8111'),
        //   dictItems: this.createDictList('8111'),
        //   showOverflowTooltip: true
        // },
        {
          title: '出库日期',
          dataIndex: 'SEND_TIME',
          // dateFormat: 'yyyy-MM-dd hh:mm:ss',
          sorter: true,
          filter: true,
          filterType: 'date-range',
          showOverflowTooltip: true,
          exportFormat: {
            t: 'd'
          }
        },
        {
          title: '客户名称',
          dataIndex: 'OWNER_NAME',
          sorter: true,
          filter: true,
          filterType: 'input',
          showOverflowTooltip: true
        },
        {
          title: '牌照号',
          dataIndex: 'LICENSE',
          sorter: true,
          filter: true,
          filterType: 'input',
          showOverflowTooltip: true
        },
        {
          title: '仓库名称',
          dataIndex: 'STORAGE_CODE',
          dictItems: [],
          editItems: [],
          sorter: true,
          filter: true,
          filterType: 'input',
          showOverflowTooltip: true
        },
        // {
        //   title: '税率',
        //   dataIndex: 'fake4',
        //   sorter: true,
        //   filter: true,
        //   filterType: 'input',
        //   showOverflowTooltip: true
        // },
        {
          title: '维修技师',
          dataIndex: 'RECEIVER_NAME',
          sorter: true,
          filter: true,
          filterType: 'input',
          dictItems: [],
          filter: true,
          filterItems: [],
          showOverflowTooltip: true
        },
        {
          title: '服务顾问',
          dataIndex: 'SERVICE_ADVISOR',
          sorter: true,
          filter: true,
          filterType: 'checkbox',
          dictItems: [],
          filter: true,
          filterItems: [],
          showOverflowTooltip: true
        },
        {
          title: '操作员代码',
          dataIndex: 'SENDER',
          sorter: true,
          filter: true,
          filterType: 'input',
          showOverflowTooltip: true
        },
        {
          title: '操作员名称',
          dataIndex: 'OPERATOR_NAME',
          // render: params => {
          //   return <span>{this.userList[params.row.OPERATOR_NAME]}</span>;
          // },
          editable: false,
          editType: 'select',
          editItems: [],
          dictItems: [],
          filter: true,
          filterItems: [],
          showOverflowTooltip: true
        },
        {
          title: '配件代码',
          dataIndex: 'PART_NO',
          sorter: true,
          filter: true,
          filterType: 'input',
          width: '160',
          showOverflowTooltip: true
        },
        // {
        //   title: '批号',
        //   dataIndex: 'fake6',
        //   sorter: true,
        //   filter: true,
        //   filterType: 'input',
        //   showOverflowTooltip: true
        // },
        {
          title: '配件名称',
          dataIndex: 'PART_NAME',
          sorter: true,
          filter: true,
          filterType: 'input',
          showOverflowTooltip: true
        },
        // {
        //   title: '配件说明',
        //   dataIndex: 'PART_DESCRIPTION',
        //   sorter: true,
        //   filter: true,
        //   filterType: 'input',
        //   showOverflowTooltip: true
        // },
        // {
        //   title: 'CCC件类型',
        //   dataIndex: 'IS_CCC_PART',
        //   sorter: true,
        //   filter: true,
        //   filterType: 'input',
        //   showOverflowTooltip: true
        // },
        // {
        //   title: '保质期',
        //   dataIndex: 'SHELF_LIFT_MARK'
        // },
        // {
        //   title: 'ABC分类',
        //   dataIndex: 'ABC_TYPE',
        //   sorter: true,
        //   filter: true,
        //   filterType: 'checkbox',
        //   filterItems: this.createDictList('8092'),
        //   dictItems: this.createDictList('8092'),
        //   render: props => {
        //     return <span>{this.createDictText(props.row.ABC_TYPE, '8092')}</span>;
        //   }
        // },
        // {
        //   title: '计量单位',
        //   dataIndex: 'UNIT_NAME',
        //   sorter: true,
        //   filter: true,
        //   filterType: 'input',
        //   showOverflowTooltip: true
        // },
        {
          title: '出库数量',
          dataIndex: 'PART_QUANTITY',
          summation: true,
          precision: 2,
          sorter: true,
          filter: true,
          filterType: 'number',
          summationDataIndex: 'TOTAL_PART_QUANTITY',
          showOverflowTooltip: true,
          exportFormat: {
            t: 'n'
          }
        },
        {
          title: '含税出库单价',
          dataIndex: 'PART_SALES_PRICE',
          precision: 2,
          sorter: true,
          filter: true,
          filterType: 'input',
          summation: false,
          summationDataIndex: 'TOTAL_PART_SALES_PRICE',
          showOverflowTooltip: true
        },
        {
          title: '含税成本单价',
          dataIndex: 'PART_COST_PRICE',
          precision: 2,
          sorter: true,
          filter: true,
          filterType: 'number',
          showOverflowTooltip: true,
          exportFormat: {
            t: 'n'
          }
        },
        {
          title: '含税出库金额',
          dataIndex: 'PART_SALES_AMOUNT',
          precision: 2,
          summation: true,
          summationDataIndex: 'TOTAL_PART_SALES_AMOUNT',
          sorter: true,
          filter: true,
          filterType: 'number',
          showOverflowTooltip: true,
          exportFormat: {
            t: 'n'
          }
        },
        {
          title: '含税成本金额',
          dataIndex: 'PART_COST_AMOUNT',
          summation: true,
          precision: 2,
          sorter: true,
          filter: true,
          filterType: 'number',
          summationDataIndex: 'TOTAL_PART_COST_AMOUNT',
          showOverflowTooltip: true,
          exportFormat: {
            t: 'n'
          }
        }
        // {
        //   title: '主组号',
        //   dataIndex: 'MAIN_GROUP_NO',
        //   sorter: true,
        //   filter: true,
        //   filterType: 'input',
        //   showOverflowTooltip: true
        // },
        // {
        //   title: '销售方式',
        //   dataIndex: 'SALES_TYPE',
        //   sorter: true,
        //   filter: true,
        //   filterType: 'input',
        //   showOverflowTooltip: true
        // },
        // {
        //   title: '发布单号',
        //   dataIndex: 'fake7',
        //   sorter: true,
        //   filter: true,
        //   filterType: 'input',
        //   showOverflowTooltip: true
        // }
        // {
        //   title: '结算单号',
        //   dataIndex: 'BALANCE_NO',
        //   sorter: true
        // },
        // {
        //   title: '工单号',
        //   dataIndex: 'RO_NO',
        //   sorter: true
        // },
        // {
        //   title: '车主编号',
        //   dataIndex: 'OWNER_NO',
        //   sorter: true
        // },
        // {
        //   title: '车牌号',
        //   dataIndex: 'LICENSE',
        //   sorter: true
        // },
        // {
        //   title: '车主',
        //   dataIndex: 'OWNER_NAME',
        //   sorter: true
        // },
        // {
        //   title: '发料单号',
        //   dataIndex: 'OUT_STOCK_NO',
        //   sorter: true
        // },
        // {
        //   title: '实收金额',
        //   dataIndex: 'PART_SALES_AMOUNT',
        //   sorter: true
        // },
        // {
        //   title: '维修类型',
        //   dataIndex: 'REPAIR_TYPE_CODE',
        //   sorter: true,
        //   editable: false,
        //   editType: 'select',
        //   editItems: []
        // },
        // {
        //   title: '车型',
        //   dataIndex: 'MODEL',
        //   sorter: true,
        //   editable: false,
        //   editType: 'select',
        //   editItems: []
        // },
        // {
        //   title: '工单开单日期',
        //   dataIndex: 'RO_CREATE_DATE',
        //   sorter: true
        // },
        // {
        //   title: 'VIN',
        //   dataIndex: 'VIN',
        //   sorter: true
        // },
        // {
        //   title: '工单类型',
        //   dataIndex: 'RO_TYPE',
        //   sorter: true,
        //   render: props => {
        //     return <span>{this.createDictText(props.row.RO_TYPE, '8068')}</span>;
        //   }
        // },
        // {
        //   title: '发料人',
        //   dataIndex: 'SENDER',
        //   sorter: true
        // },
        // {
        //   title: '发料时间',
        //   dataIndex: 'SEND_TIME',
        //   sorter: true,
        //   editable: false,
        //   width: '160',
        //   editType: 'select',
        //   editItems: []
        // },
        // {
        //   title: '服务专员',
        //   dataIndex: 'SERVICE_ADVISOR',
        //   sorter: true,
        //   editable: false,
        //   editType: 'select',
        //   editItems: []
        // },
        // {
        //   title: '仓库',
        //   dataIndex: 'STORAGE_CODE',
        //   sorter: true,
        //   editable: false,
        //   editType: 'select',
        //   editItems: []
        // }
      ];
    },

    async initTableData(obj) {
      const fetchParamObj = this.fetchParamObj;
      this.fetchParams = Object.assign({}, fetchParamObj, { xhrAbort: false });
      // this.fetchParams = Object.assign({}, fetchParamObj);
      // try {
      //   this.$refs.table.START_LOADING();
      //   this.dataSource = [];
      //   let res = await queryPartInOutStockReport(this.fetchParams);
      //   this.dataSource = res.data;
      //   this.$refs.table.STOP_LOADING();
      // } catch (error) {
      //   console.log(error);
      // } finally {
      //   this.$refs.table.STOP_LOADING();
      // }
    },

    // 获取仓库
    async getStorage() {
      const res = await getStroageList();
      this.columns.find(x => x.dataIndex === 'STORAGE_CODE').dictItems = this.columns.find(x => x.dataIndex === 'STORAGE_CODE').editItems = res.data.map(x => ({
        text: x.STORAGE_NAME,
        value: x.STORAGE_CODE + ''
      }));
    },

    // 查询所有车型(供table使用)
    async queryModel() {
      const res = await getModel();
      this.columns.find(x => x.dataIndex === 'MODEL').editItems = res.data.map(x => ({ text: x.MODEL_NAME, value: x.MODEL_ID + '' }));
    },

    // 获取维修项目类型
    async getWxtypeSelect() {
      const res = await getWxlxSelect();
      this.columns.find(x => x.dataIndex === 'REPAIR_TYPE_CODE').editItems = res.data.map(x => ({
        value: x.REPAIR_TYPE_CODE + '',
        text: x.REPAIR_TYPE_NAME
      }));
    },

    // 售前人员接口数据
    async serviceConsultant() {
      let consultant = { role: dictCode.SERVICE_CONSULTANT }; // 服务专员
      const consultantRes = await searchRoleByCode(consultant);
      this.columns.find(x => x.dataIndex === 'SERVICE_ADVISOR').editItems = consultantRes.data.map(x => ({ text: x.employeeName, value: x.userId + '' }));
    },

    // 操作员名称
    async getEmployee() {
      // 获取人员列表
      const res = await getAllUser();
      if (res.resultCode == 200) {
        res.data.map(e => {
          this.cunUserList[e.userId + ''] = e.employeeName;
        });
        this.columns.find(item => item.dataIndex === 'OPERATOR_NAME').editItems = this.columns.find(item => item.dataIndex === 'OPERATOR_NAME').dictItems = this.columns.find(
          item => item.dataIndex === 'OPERATOR_NAME'
        ).filterItems = res.data.map(x => ({
          text: x.employeeName,
          value: x.userId + ''
        }));
        this.columns.find(item => item.dataIndex === 'RECEIVER_NAME').dictItems = this.columns.find(item => item.dataIndex === 'RECEIVER_NAME').filterItems = res.data.map(x => ({
          text: x.employeeName,
          value: x.userId + ''
        }));
        this.columns.find(item => item.dataIndex === 'SERVICE_ADVISOR').dictItems = this.columns.find(item => item.dataIndex === 'SERVICE_ADVISOR').filterItems = res.data.map(x => ({
          text: x.employeeName,
          value: x.userId + ''
        }));
      }
    },
    // 维修项目table数据改变（翻译多人技师）
    async maintenanceSyncDataFun(e) {
      console.log(e, 'table1数据变化');
      if (!Object.keys(this.salerData).length) {
        let technician = { role: dictCode.TECHNICIAN };
        const technicianRes = await searchRoleByCodes(technician);
        let obj = {};
        technicianRes.data.map(item => {
          obj[item.userId] = item.employeeName;
        });
        this.salerData = obj;
      }
      await sleep(600);
      this.$nextTick(() => {
        e.map(item => {
          let arr = item.CHIEF_TECHNICIAN ? item.CHIEF_TECHNICIAN.split(',') : [];
          let nameArr = [];
          arr.map(item2 => {
            nameArr.push(this.salerData[item2]);
          });
          item.TECHNICIAN_NAMES_TRANSED = nameArr.join(',');
        });
      });
    }
  }
};
</script>

<style lang="less" scoped>
/* .form-group {
  margin-top: 10px;
  span {
    height: 50px;
    line-height: 50px;
    text-align: right;
    width: 250px;
    padding-left: 100px;
  }
} */
</style>
